package com.ss.project.xia17user.config.security;

import com.ss.project.xia17user.config.security.form.FormAuthentication;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * security常用方法
 * @author xia17
 * @since 2020/9/16 17:40
 */
public class SecurityUtils {


    public static String username(){
        return getAuthentication().getName();
    }

    public static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static Long userId(){
        Authentication authentication = getAuthentication();
        if (authentication instanceof FormAuthentication){
            return ((FormAuthentication) authentication).getUser().getId();
        }
        return null;
    }

    /**
     * 获取权限信息
     * @return /
     */
    public static List<String> getAuthorities(){
        return getAuthentication().getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
    }


}
